package com.wonderful.compose.overlap

import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wonderful.compose.databinding.ItemListBinding

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/2/19 11:02
 */
class DogsAdapter : RecyclerView.Adapter<DogsAdapter.ViewHolder>() {

    private val differ = AsyncListDiffer(this, object : DiffUtil.ItemCallback<Int>() {
        override fun areItemsTheSame(oldItem: Int, newItem: Int): Boolean = oldItem == newItem

        override fun areContentsTheSame(oldItem: Int, newItem: Int): Boolean = oldItem == newItem
    })

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: DogsAdapter.ViewHolder, position: Int) {
        holder.bind(differ.currentList[position])
    }

    override fun getItemCount(): Int {
        return differ.currentList.size
    }

    fun submitData(list: List<Int>) {
        differ.submitList(list)
    }

    inner class ViewHolder(private val binding: ItemListBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(resId: Int) {
            binding.img.setImageResource(resId)
        }
    }
}

class OverlappingDecoration : RecyclerView.ItemDecoration() {
    private val overlapPercentage = 15

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val with = view.layoutParams.width
        val widthPercentage = (overlapPercentage * with * -1) / 100
        val position = parent.getChildAdapterPosition(view)
        val isReversed = (parent.layoutManager as? LinearLayoutManager)?.reverseLayout ?: false
        if (position == 0) {
            return
        } else {
            if (isReversed) {
                outRect.set(0, 0, widthPercentage, 0)
            } else {
                outRect.set(widthPercentage, 0, 0, 0)
            }
        }
    }
}